package com.itheima.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Mapper.OrderMapper;
import com.itheima.Service.OrderService;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderQueryParam;
import com.itheima.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public PageResult<Order> page(OrderQueryParam queryParam) {
        PageHelper.startPage(queryParam.getPage(), queryParam.getPageSize());
        List<Order> orderList = orderMapper.list(queryParam);
        Page<Order> page = (Page<Order>) orderList;
        return new PageResult<>((int) page.getTotal(), orderList);
    }

    @Override
    public Order get(Integer id) {
        return orderMapper.get(id);
    }

    @Override
    public void add(Order order) {
        // 补全基础信息
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        // 生成订单编号
        order.setOrderNumber(generateOrderId());
        orderMapper.insert(order);
    }

    @Override
    public void update(Order order) {
        order.setUpdateTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    @Override
    public void updateStatus(Integer id, String status) {
        orderMapper.updateStatus(id, status);
    }

    @Override
    public void delete(Integer id) {
        orderMapper.delete(id);
    }

    // 生成订单编号
    private String generateOrderId() {
        return "ORD-" + System.currentTimeMillis();
    }
}